package com.itheima.safe.mq;

import com.alibaba.fastjson.JSON;
import com.itheima.common.pojo.VerifyMessage;
import com.itheima.dfs.feign.DfsFeign;
import com.itheima.safe.service.AliyunSafeService;
import com.itheima.safe.util.MatchUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class VerifyConsumer {
    @Autowired
    private AliyunSafeService aliyunSafeService;

    @Autowired
    private DfsFeign dfsFeign;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 内容安全检测
     */
    @KafkaListener(topics = "checkfortext",groupId = "safegroup")
    public void verifySafe(ConsumerRecord<?,?> record) throws Exception {

        //得到内容
        String content = record.value().toString();
        //整个内容安全及那侧
        VerifyMessage verifyMessage = JSON.parseObject(content, VerifyMessage.class);
        //得到verifyContent的内容
        String verifyContent = verifyMessage.getContent();

        boolean result = true;
        //文本进行检测，去掉url地址
        if(!aliyunSafeService.verifyContent(Collections.singletonList(MatchUtil.replateUrl(verifyContent)))){
            //检测不通过
            result=false;
        }
        List<String> images = MatchUtil.matchImages(verifyContent);
        //文件的字节数组
        if (images != null && images.size()>0){
            //批量下载
            List<byte[]> imagesBytes = dfsFeign.download(images);
            if (!aliyunSafeService.verifyImage(imagesBytes)){
                //检测不通过
                result = false;
            }
        }
        //将数据返回给调用者
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("attach",verifyMessage.getAttach());
        resultMap.put("result",result);
        kafkaTemplate.send(verifyMessage.getBackqueue(),JSON.toJSONString(resultMap));

    }



}
